package com.rgp.apipassenger.controller;

import com.rgp.internalcommon.common.CommonStatusEnum;
import com.rgp.internalcommon.common.VerificationCodeConstant;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.dto.VerificationCodeDto;
import com.rgp.apipassenger.service.VerificationCodeService;
import com.rgp.internalcommon.utils.PatternCheckUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-10 20:46
 */
@RestController
public class VerificationCodeController {

    @Autowired
    private VerificationCodeService verificationCodeService;

    @GetMapping("/verification-code")
    public ResponseResult verification(@RequestBody VerificationCodeDto verificationCodeDto){

        //1.接收用户发送的手机号
        String passengerPhone = verificationCodeDto.getUserPhone();

        //2.校验手机号
        //System.out.println("校验手机号");
        if(!PatternCheckUtils.isValidPhone(passengerPhone)){
            return ResponseResult.fail(CommonStatusEnum.PHONENUMBER_ERROR);
        }

        //3.生成验证码
        String verificationCode = verificationCodeService.getVerificationCode(passengerPhone);

        //4.返回成功
        if (verificationCode != null){
            return ResponseResult.success();
        }else{
            return ResponseResult.fail(CommonStatusEnum.FAIL_SEND_VERIFICATIONCODE_ERROR);
        }
    }

    @PostMapping("/check-verificationcode")
    public ResponseResult checkVerificationCode(@RequestBody VerificationCodeDto verificationCodeDto){

        //1.接收手机号与验证码
        String passengerPhone = verificationCodeDto.getUserPhone();
        String numberCode = verificationCodeDto.getNumberCode();

        //2.校验手机号的格式与验证码的长度
        if (!PatternCheckUtils.isValidPhone(passengerPhone)){
            return ResponseResult.fail(CommonStatusEnum.PHONENUMBER_ERROR);
        }else if(StringUtils.isEmpty(numberCode) || numberCode.length() != VerificationCodeConstant.VERIFICATION_CODE_SIZE){
            return ResponseResult.fail(CommonStatusEnum.VERIFICATIONCODE_ERROR);
        }

        //3.根据手机号取出验证码并进行校验,完成用户的注册与登录，颁发token给用户
        ResponseResult result = verificationCodeService.checkVerificationCode(passengerPhone, numberCode);

        //4.返回token
        return result;
    }

    @GetMapping("auth-token")
    public ResponseResult authToken(@RequestHeader("Authorization") String token){
        System.out.println("token:" + token);
        return ResponseResult.success();
    }

    @GetMapping("no-auth-token")
    public ResponseResult noAuthToken(@RequestHeader("Authorization") String token){
        System.out.println("token:" + token);
        return ResponseResult.fail();
    }
}
